layui.define(['table', 'jquery', 'form','treeTable'], function (exports) {
    "use strict";

    var MOD_NAME = 'tableSelect',
        $ = layui.jquery,
        form = layui.form;
    var tableSelect = function () {
        this.v = '1.1.0';
    };


    /** 渲染过的控件数据 */
    var tableSelectArr = [];


    /**
    * 初始化表格选择器
    */
    tableSelect.prototype.render = function (opt) {
        

        var elem = opt.elem
        if (!(elem instanceof jQuery)) {
            elem = $(opt.elem);
        }
        var tableDone = opt.table.done || function () { };

        var  table = opt.tabletype === 'treeTable' ? layui.treeTable : layui.table;
        //默认设置
        opt.searchKey = opt.searchKey || 'keyword';
        opt.searchPlaceholder = opt.searchPlaceholder || '关键词搜索';
        opt.checkedKey = opt.checkedKey;
        opt.table.page = opt.table.page || true;
        opt.table.height = opt.table.height || 315;

        

        var tableName = "tableSelect_table_" + new Date().getTime() + parseInt(Math.random() * (100 - 1 + 1) + 1, 10);

        elem.off('click').on('click', function (e) {
            e.stopPropagation();

            //if ($('div.tableSelect').length >= 1) {
            //    return false;
            //}
            if ($('#div_' + tableName+'.tableSelect').length >= 1) {
                return false;
            }

            var t = elem.offset().top + elem.outerHeight() + "px";
            var l = elem.offset().left + "px";
          
            var tableBox = '<div id="div_' + tableName+'" class="tableSelect layui-anim layui-anim-upbit" style="left:' + l + ';top:' + t + ';border: 1px solid #d2d2d2;background-color: #fff;box-shadow: 0 2px 4px rgba(0,0,0,.12);padding:10px 10px 0 10px;position: absolute;z-index:66666666;margin: 5px 0;border-radius: 2px;min-width:530px;">';
            tableBox += '<div class="tableSelectBar">';
            tableBox += '<form class="layui-form" action="" style="display:inline-block;">';
            tableBox += '<input style="display:inline-block;width:190px;height:30px;vertical-align:middle;margin-right:-1px;border: 1px solid #C9C9C9;" type="text" name="' + opt.searchKey + '" placeholder="' + opt.searchPlaceholder + '" autocomplete="off" class="layui-input"><button class="layui-btn layui-btn-sm layui-btn-primary tableSelect_btn_search" lay-submit lay-filter="tableSelect_btn_search"><i class="layui-icon layui-icon-search"></i></button>';
            tableBox += '</form>';
            tableBox += '<button style="margin-left:20px;" class="layui-btn layui-btn-sm layui-btn-radius tableSelect_btn_select">选择<span></span></button>';
            tableBox += '<button style="margin-left:10px;" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger tableSelect_btn_clear">清空</button>';
            
       
            tableBox += '</div>';
            tableBox += '<table id="' + tableName + '" lay-filter="' + tableName + '"></table>';
            tableBox += '</div>';
            tableBox = $(tableBox);
            $('body').append(tableBox);

            //数据缓存
            var checkedData = [];

            //渲染TABLE
            opt.table.elem = "#" + tableName;
            opt.table.id = tableName;
            opt.table.done = function (res, curr, count) {

                if (opt.tabletype === 'treeTable') {
                    defaultChecked({ data: res}, curr, count);
                    setChecked({ data: res }, curr, count);
                    tableDone({ data: res }, curr, count);
                }
                else {
                    if (res.code === -420) {
                        //重新渲染数据 3秒后
                        setTimeout(function () {
                            tableSelect_table.reload({
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            });
                            //只重载数据
                        }, 3000);
                    }
                    else {
                        defaultChecked(res, curr, count);
                        setChecked(res, curr, count);
                        tableDone(res, curr, count);
                    }
                }  


              


             
            };
            var tableSelect_table = table.render(opt.table);

            //分页选中保存数组
            table.on('radio(' + tableName + ')', function (obj) {
                var disabled = undefined;
                if (opt.tabletype === 'treeTable') {
                    disabled = obj.data[opt.table.tree.disabledName];
                }
                else {
                    disabled = obj.data[opt.table.disabledName];
                }

                if (disabled !== undefined) disabled = disabled === false || disabled === 'false';
                if (disabled) return;

                if (opt.checkedKey) {
                    if (opt.tabletype === 'treeTable') {
                        checkedData = tableSelect_table.checkStatus();
                    }
                    else {
                        checkedData = table.checkStatus(tableName).data
                    }  
                }

                if (opt.tabletype === 'treeTable') {
                    updataButton(tableSelect_table.checkStatus().length)
                }
                else {

                    updataButton(table.checkStatus(tableName).data.length)
                }  
            })
            table.on('checkbox(' + tableName + ')', function (obj) {
                var disabled = undefined;
                if (opt.tabletype === 'treeTable') {
                    disabled = obj.data[opt.table.tree.disabledName];
                }
                else {
                    disabled = obj.data[opt.table.disabledName];
                }

                if (disabled !== undefined) disabled = disabled === false || disabled === 'false';
                if (disabled) return;

                if (opt.checkedKey) {
                    if (obj.checked) {
                        if (opt.tabletype === 'treeTable') {
                            for (var i = 0; i < tableSelect_table.checkStatus().length; i++) {
                                checkedData.push(tableSelect_table.checkStatus()[i])
                            }
                        }
                        else
                        {
                            for (var i = 0; i < table.checkStatus(tableName).data.length; i++) {
                                checkedData.push(table.checkStatus(tableName).data[i])
                            }
                        }


                    } else {
                        if (obj.type == 'all') {
                            for (var j = 0; j < table.cache[tableName].length; j++) {
                                for (var i = 0; i < checkedData.length; i++) {
                                    if (checkedData[i][opt.checkedKey] == table.cache[tableName][j][opt.checkedKey]) {
                                        checkedData.splice(i, 1)
                                    }
                                }
                            }
                        } else {
                            //因为LAYUI问题，操作到变化全选状态时获取到的obj为空，这里用函数获取未选中的项。
                            function nu() {
                                var noCheckedKey = '';
                                for (var i = 0; i < table.cache[tableName].length; i++) {
                                    if (!table.cache[tableName][i].LAY_CHECKED) {
                                        noCheckedKey = table.cache[tableName][i][opt.checkedKey];
                                    }
                                }
                                return noCheckedKey
                            }
                            var noCheckedKey = obj.data[opt.checkedKey] || nu();
                            for (var i = 0; i < checkedData.length; i++) {
                                if (checkedData[i][opt.checkedKey] == noCheckedKey) {
                                    checkedData.splice(i, 1);
                                }
                            }
                        }
                    }
                    checkedData = uniqueObjArray(checkedData, opt.checkedKey);
                    updataButton(checkedData.length)
                } else {
                    if (opt.tabletype === 'treeTable') {
                        updataButton(tableSelect_table.checkStatus().length);
                    }
                    else {
                        updataButton(table.checkStatus(tableName).data.length);
                    }

                    


                }
            });

            //渲染表格后选中
            function setChecked(res, curr, count) {
                if (res!=null && res.data!=null) {
                    for (var i = 0; i < res.data.length; i++) {
                        for (var j = 0; j < checkedData.length; j++) {
                            if (res.data[i][opt.checkedKey] == checkedData[j][opt.checkedKey]) {

                                res.data[i].LAY_CHECKED = true;
                                if (opt.tabletype === 'treeTable') {

                                    tableSelect_table.setChecked([res.data[i][tableSelect_table.options.tree.idName]]); 
                                }
                                else
                                {
                                    var index = res.data[i]['LAY_TABLE_INDEX'];
                                    var checkbox = $('#' + tableName + '').next().find('tr[data-index=' + index + '] input[type="checkbox"]');
                                    checkbox.prop('checked', true).next().addClass('layui-form-checked');
                                    var radio = $('#' + tableName + '').next().find('tr[data-index=' + index + '] input[type="radio"]');
                                    radio.prop('checked', true).next().addClass('layui-form-radioed').find("i").html('&#xe643;');
                                }
                            }
                        }
                    }
                }

                if (opt.tabletype !== 'treeTable') {
                    var checkStatus = table.checkStatus(tableName);

                    if (checkStatus.isAll) {
                        $('#' + tableName + '').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                        $('#' + tableName + '').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                }

                updataButton(checkedData.length)
            }

            //写入默认选中值(puash checkedData)
            function defaultChecked(res, curr, count) {
                if (opt.checkedKey && elem.attr('ts-selected')) {
                    var selected = elem.attr('ts-selected').split(",");
                    for (var i = 0; i < res.data.length; i++) {
                        for (var j = 0; j < selected.length; j++) {
                            if (res.data[i][opt.checkedKey] == selected[j]) {
                                checkedData.push(res.data[i])
                            }
                        }
                    }
                    checkedData = uniqueObjArray(checkedData, opt.checkedKey);
                }
            }

            //更新选中数量
            function updataButton(n) {
                tableBox.find('.tableSelect_btn_select span').html(n == 0 ? '' : '(' + n + ')')
            }

            //数组去重
            function uniqueObjArray(arr, type) {
                var newArr = [];
                var tArr = [];
                if (arr.length == 0) {
                    return arr;
                } else {
                    if (type) {
                        for (var i = 0; i < arr.length; i++) {
                            if (!tArr[arr[i][type]]) {
                                newArr.push(arr[i]);
                                tArr[arr[i][type]] = true;
                            }
                        }
                        return newArr;
                    } else {
                        for (var i = 0; i < arr.length; i++) {
                            if (!tArr[arr[i]]) {
                                newArr.push(arr[i]);
                                tArr[arr[i]] = true;
                            }
                        }
                        return newArr;
                    }
                }
            }

            //FIX位置
            var overHeight = (elem.offset().top + elem.outerHeight() + tableBox.outerHeight() - $(window).scrollTop()) > $(window).height();
            var overWidth = (elem.offset().left + tableBox.outerWidth()) > $(window).width();
            overHeight && tableBox.css({ 'top': 'auto', 'bottom': '0px' });
            overWidth && tableBox.css({ 'left': 'auto', 'right': '5px' })

            //关键词搜索
            form.on('submit(tableSelect_btn_search)', function (data) {
                if (opt.tabletype === 'treeTable') {
                    //查询历史参数
                    var where = {};
                    if (tableSelect_table.options.where) {
                        where = tableSelect_table.options.where;
                        for (var key in data.field) {
                            where[key] = data.field[key];
                        }
                    }
                    tableSelect_table.reload({
                        where: where
                    });

                    //去筛选值
                    for (var key1 in data.field) {
                        for (var i in tableSelect_table.options.where) {
                            if (i === key1) {
                                //删除where 筛选条件 省的展开数据会造成加载下级也传参了 
                                delete tableSelect_table.options.where[i];
                            }
                            if (i === tableSelect_table.options.tree.pidName) {
                                //删除下拉加载的下级ID
                                delete tableSelect_table.options.where[i];
                            }
                        }
                    }

                   
                }
                else
                {
                    tableSelect_table.reload({
                        where: data.field,
                        page: {
                            curr: 1
                        }
                    });
                }

              
                data.form.children[0].focus();
                return false;
            });

            //双击行选中
            table.on('rowDouble(' + tableName + ')', function (obj) {
                var disabled = undefined;
                if (opt.tabletype === 'treeTable') {
                    disabled = obj.data[opt.table.tree.disabledName];
                }
                else
                {
                    disabled = obj.data[opt.table.disabledName];
                }
                if (disabled !== undefined) disabled = disabled === false || disabled === 'false';
                if (disabled) return;

                var checkStatus = { data: [obj.data] };
                selectDone(checkStatus);
            })

            tableBox.find('.tableSelect_btn_clear').on('click', function ()
            {
                selectDone({ data: [] });
            })
            //按钮选中
            tableBox.find('.tableSelect_btn_select').on('click', function () {
                var checkStatus = {};
                if (opt.tabletype === 'treeTable') {
                    checkStatus = { data: tableSelect_table.checkStatus()};
                }
                else {
                    checkStatus = table.checkStatus(tableName);
                }
                if (checkedData.length > 1) {
                    checkStatus.data = checkedData;
                }
                selectDone(checkStatus);
            })

            //写值回调和关闭
            function selectDone(checkStatus) {
                if (opt.checkedKey) {
                    var selected = [];
                    for (var i = 0; i < checkStatus.data.length; i++) {
                        selected.push(checkStatus.data[i][opt.checkedKey])
                    }
                    elem.attr("ts-selected", selected.join(","));
                }
                opt.done(elem, checkStatus);
                tableBox.remove();
                if (opt.tabletype !== 'treeTable') {
                    delete table.cache[tableName];
                }
                checkedData = [];
            }

            //点击其他区域关闭
            $(document).mouseup(function (e) {
                //var userSet_con = $('' + opt.elem + ',.tableSelect');
                
                var userSet_con = $('#div_' + tableName + '.tableSelect');
                if (userSet_con.length>0) {
                    var userSet_elem = elem;
                    if (!userSet_con.is(e.target) && userSet_con.has(e.target).length === 0
                        && !userSet_elem.is(e.target) && userSet_elem.has(e.target).length === 0
                    ) {
                        tableBox.remove();
                        if (opt.tabletype !== 'treeTable') {
                            delete table.cache[tableName];
                        }
                        checkedData = [];
                    }
                }

            });
        })
    }

    /**
    * 隐藏选择器
    */
    tableSelect.prototype.hide = function (opt) {
        $('.tableSelect').remove();
    }


    //自动完成渲染
    var tt = {

        render: function (opt){
            //渲染
            new tableSelect().render(opt);

            
        }
    }

    //FIX 滚动时错位
    if (window.top == window.self) {
        $(window).scroll(function () {
            //tableSelect.hide();
            $('.tableSelect').remove();
        });
    }



    exports(MOD_NAME, tt);
})